<template>
  <div v-loading="loading">
    <div v-if="hasContract">
      <div class="text-right" v-if="!editable">
        <el-button size="small" class="mb-2 d-print-none" @click="handlePrint">
          <i class="fa fa-print"></i>
          打印
        </el-button>
      </div>

      <div :id="printId">
        <table class="mb-0 table table-borderless text-center">
          <colgroup>
            <col width="16%" />
            <col width="17%" />
            <col width="17%" />
            <col width="16%" />
            <col width="17%" />
            <col width="17%" />
          </colgroup>
          <tr>
            <td colspan="6" class="text-center border-0">
              <h5>业务合同审批表{{ processLabel }}</h5>
            </td>
          </tr>
          <tr>
            <td class="text-left">部门：</td>
            <td></td>
            <td>填表人：</td>
            <td></td>
            <td>日期：</td>
            <td></td>
          </tr>
        </table>
        <table class="table table-bordered vertical-align-middle text-center">
          <colgroup>
            <col width="15%" />
            <col width="30%" />
            <col width="15%" />
            <col width="40%" />
          </colgroup>
          <tbody>
            <tr>
              <td>客户名称</td>
              <td>{{ related.customer_name }}</td>
              <td>客户类型</td>
              <td>{{ orgClassName }}</td>
            </tr>
            <tr>
              <td>担保额度</td>
              <td>{{ entrustContract.reply_funds }}万元</td>
              <td>担保期限</td>
              <td>{{ entrustContract.load_years }}月</td>
            </tr>
            <tr>
              <td>担保费率</td>
              <td>{{ entrustContract.gua_rate || '-' }}%</td>
              <td>合同期间</td>
              <td>{{ loadPeriod }}</td>
            </tr>
            <tr>
              <td>放款机构</td>
              <td>{{ entrustContract.bank_name || '-' }}</td>
              <td>贷款品种</td>
              <template v-if="!editable">
                <td>{{ loadVarietiesStr }}</td>
              </template>
              <template v-else>
                <td class="input-td">
                  <c-select
                    class="w-100 variety-selector"
                    popper-class="text-center"
                    :options="enumLoanVarieties"
                    v-model="loadVarieties"
                    number-key
                    placeholder="请选择"
                  ></c-select>
                </td>
              </template>
            </tr>
            <tr>
              <td>放款利率</td>
              <td>{{ entrustContract.load_rate || '-' }}%</td>
              <td>贷款实际用途</td>
              <td>{{ entrustContract.funds_use_dir || '' }}</td>
            </tr>
            <tr>
              <td>反担保方式</td>
              <td colspan="3" class="text-left">
                <ul class="list-inline">
                  <li class="list-inline-item mr-5" v-for="(guad, index) in guadTypes" :key="index">
                    <checked-box :value="guad.value"></checked-box>
                    <span>{{ guad.label }}</span>
                  </li>
                </ul>
              </td>
            </tr>
            <tr>
              <td>反担保措施</td>
              <td colspan="3">
                <ul class="list-unstyled text-left">
                  <li v-for="(guad, index) in guardCombines" :key="guad.id">
                    <span>{{ index + 1 }}、</span>
                    <span>{{ guad.combineStr }}</span>
                  </li>
                </ul>
              </td>
            </tr>
            <tr>
              <td>业务合同类型</td>
              <td colspan="3">
                <ul class="list-unstyled text-left">
                  <li
                    v-for="(bc, index) in busContracts"
                    :key="index"
                    class="d-flex align-items-center"
                  >
                    <checked-box :value="bc.value" class="mr-3"></checked-box>
                    <div style="min-width: 180px">{{ bc.label }}</div>
                    <div v-if="bc.showNum">
                      <el-input
                        v-model="bc.num"
                        class="my-1"
                        size="mini"
                        style="width: 130px"
                        v-input-number="{ min: 0, fixed: 0 }"
                        @blur="setValue(bc)"
                        v-if="editable"
                      >
                        <span slot="append">份</span>
                      </el-input>
                      <div style="min-width: 180px" v-else>{{ bc.num }}份</div>
                    </div>
                    <div v-if="bc.attach">
                      <div v-if="editable" class="d-flex align-items-center">
                        <div class="mr-3">
                          <input
                            type="file"
                            ref="uploadInput"
                            class="d-none"
                            multiple
                            accept="*"
                            @change="handleFileChange"
                          />
                          <el-button
                            plain
                            size="mini"
                            class="ml-3"
                            icon="el-icon-upload2"
                            :disabled="saveLoading"
                            @click="handleSelectFile"
                          >
                            上传
                          </el-button>
                        </div>
                        <div class="flex-1 bg-light p-2 rounded">
                          <div v-for="(file, i) in areadyFiles" :key="file.url" class="file-item">
                            <div>
                              {{ file.name }}
                              <el-button
                                type="text"
                                :disabled="saveLoading"
                                @click="handleDeleteFile(1, i)"
                              >
                                删除
                              </el-button>
                            </div>
                          </div>
                          <div v-for="(file, index) in uploadFiles" :key="index" class="file-item">
                            <div>
                              {{ file.name }}
                              <el-button
                                type="text"
                                :disabled="saveLoading"
                                @click="handleDeleteFile(2, index)"
                              >
                                删除
                              </el-button>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div v-else v-for="file in areadyFiles" :key="file.url" class="file-item">
                        <div>
                          {{ file.name }}
                          <el-button type="text" @click="handleDownloadFile(file)">下载</el-button>
                        </div>
                      </div>
                    </div>
                  </li>
                </ul>
              </td>
            </tr>
            <tr>
              <td>项目经理意见</td>
              <template v-if="!editable">
                <td colspan="2">
                  <div class="text-left">{{ approval.res_a_option }}</div>
                  <sign-panel
                    sign-label="项目经理A"
                    :sign-name="approval.res_a_person"
                    :sign-date="approval.res_a_date"
                  ></sign-panel>
                </td>
                <td>
                  <div class="text-left">{{ approval.res_b_option }}</div>
                  <sign-panel
                    sign-label="项目经理B"
                    :sign-name="approval.res_b_person"
                    :sign-date="approval.res_b_date"
                  ></sign-panel>
                </td>
              </template>
              <template v-else>
                <td colspan="3" class="input-td">
                  <el-input v-model="abComment" type="textarea" placeholder="请填写"></el-input>
                  <div class="row px-3 py-2">
                    <div class="col text-left text-muted">签字：{{ related.res_a_name }}</div>
                    <div class="col text-left text-muted">日期：{{ editDate }}</div>
                  </div>
                </td>
              </template>
            </tr>
            <slot></slot>
          </tbody>
        </table>
      </div>

      <div class="text-center" v-if="editable">
        <el-button
          type="primary"
          class="btn-long"
          :disabled="loading"
          :loading="saveLoading"
          @click="handleSuccessConfirm"
        >
          提交
        </el-button>
        <el-button
          class="btn-long"
          :disabled="loading"
          :loading="saveLoading"
          @click="handleDismiss"
        >
          取消
        </el-button>
      </div>
    </div>

    <div class="p-5 bg-light rounded text-center" v-else>
      <i class="fa fa-info-circle text-muted mb-3" style="font-size: 3rem"></i>
      <div class="text-center">还没有委托担保合同</div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  enumLoanVarieties,
  enumProcessLabel,
  getRelated,
  updateRelatedContractStatus,
  getApproval,
  updateApproval,
  addApproval,
  updateContract,
} from '@/credit/views/county/unionProvince/components/contractApprove/index'
import { fileAdapter } from '@/bank/components/attach/index'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { arrayFromString, arrayToString, printA4, stringFileName } from '@vimi/utils-tool'
import { uploadOss, deleteOss } from '@/common/api/oss'
import { exportUrl } from '@/common/api/download'
export default {
  components: {
    'checked-box': {
      props: {
        value: Boolean,
      },
      render(h) {
        const { value } = this
        return h(
          'span',
          {
            style: {
              display: 'inline-block',
              verticalAlign: 'middle',
              borderWidth: '1px',
              borderStyle: 'solid',
              borderColor: value ? 'var(--primary)' : '#333',
              color: value ? 'var(--primary)' : '',
              width: '16px',
              height: '16px',
              lineHeight: '16px',
              textAlign: 'center',
              borderRadius: '2px',
              marginRight: '0.5rem',
            },
          },
          value ? [h('span', {}, '√')] : ''
        )
      },
    },
    'sign-panel': {
      props: {
        signLabel: String,
        signName: String,
        signDate: String,
      },
      render(h) {
        const date = this.$utils.dateFormat(this.signDate, 'yyyy年MM月dd日')
        return h(
          'div',
          {
            style: {
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'flex-end',
            },
          },
          [
            h(
              'div',
              {
                style: {
                  minWidth: '140px',
                },
              },
              `${this.signLabel}：${this.signName || ''}`
            ),
            h(
              'div',
              date
                ? [h('span', date)]
                : [
                    h('div', { style: { minWidth: '40px', textAlign: 'left' } }, '年'),
                    h('div', { style: { minWidth: '40px', textAlign: 'left' } }, '月'),
                    h('div', null, '日'),
                  ]
            ),
          ]
        )
      },
    },
  },
  props: {
    queryId: String,
    viewMode: Boolean,
  },
  data() {
    return {
      enumLoanVarieties,
      loading: false,
      related: {},
      approval: {},

      // 贷款品种
      loadVarieties: 1,
      // 项目经理意见
      abComment: '',

      saveLoading: false,
      busContracts: [],
      uploadFiles: [],
      areadyFiles: [],
      deleteFiles: [],
    }
  },
  computed: {
    ...mapGetters(['entrustContract', 'guardDatas', 'userId', 'enumOrgClassObj']),
    printId() {
      return `contract-approve-${this.queryId}`
    },
    editable() {
      return (
        !this.viewMode &&
        this.userId === this.related.res_a &&
        // 合同审批状态 0 待审批 1 审批中 2 待签约 3 已签约
        +this.related.contract_approval_status === 0
      )
    },
    // 是否已经提交委托担保合同
    contractId() {
      return this.entrustContract.entrust_contract_id
    },
    hasContract() {
      return !!this.contractId
    },

    // 合同审批表
    approvalId() {
      return this.approval.contract_approval_id
    },
    hasApproval() {
      return !!this.approvalId
    },

    processLabel() {
      const label = enumProcessLabel[this.related.process_status]
      return label ? `（${label}）` : ''
    },
    // 客户类型
    orgClassName() {
      return this.enumOrgClassObj[this.related.org_class] || ''
    },
    // 合同期间
    loadPeriod() {
      return (
        (this.entrustContract.load_date || '- ') +
        '至' +
        (this.entrustContract.load_end_date || ' -')
      )
    },
    // 担保期限
    calcLoadMonth() {
      const { load_date: start, load_end_date: end } = this.related
      if (start && end) {
        return this.calcMonth(start, end) || ''
      }
      return ''
    },
    // 贷款品种
    loadVarietiesStr() {
      return enumLoanVarieties[this.entrustContract.loan_varieties] || ''
    },
    // 反担保方式
    guadTypes() {
      const res = [
        { label: '保证', type: 1, value: false },
        { label: '质押', type: 2, value: false },
        { label: '抵押', type: 3, value: false },
        { label: '其他', type: 55, value: false },
        { label: '无（信用）', type: 66, value: false },
      ]
      this.busContracts.map(guad => {
        const r = res.find(it => it.type && it.type === +guad.type)
        if (r) {
          r.value = guad.value
        }
      })
      // res[4].value = this.guardDatas.length === 0
      return res
    },

    editDate() {
      return this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
    },

    // 反担保措施拼接
    guardCombines() {
      const enumCombineFn = {
        1: this.getGuadGuarantee,
        2: this.getGuadPledge,
        3: this.getGuadMortgage,
      }
      return this.guardDatas
        .filter(it => [1, 2, 3].includes(+it.gua_method))
        .map(it => ({
          id: it.gua_contract_id,
          combineStr: enumCombineFn[it.gua_method](it),
        }))
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.$store.dispatch('getEnumOrgClass')
        this.getData()
      },
      immediate: true,
    },
    entrustContract: {
      handler: function (val) {
        this.loadVarieties = +val.loan_varieties || 1
      },
      immediate: true,
      deep: true,
    },
    guardDatas: {
      handler: function () {
        this.busContracts = this.getBusContracts()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  methods: {
    handleDownloadFile(attach) {
      const { url, name } = attach
      exportUrl({
        url,
        filename: name,
      })
    },
    initForm(val = []) {
      this.areadyFiles = val.reduce((prev, curr) => {
        prev.push({
          url: curr,
          name: stringFileName(curr),
        })
        return prev
      }, [])
    },
    handleDeleteFile(type, index) {
      if (type === 2) {
        const file = this.uploadFiles[index]
        revokeObjectURL(file.url)
        this.uploadFiles.splice(index, 1)
      } else {
        this.deleteFiles.push(...this.areadyFiles.splice(index, 1))
      }
    },
    handleSelectFile() {
      const { uploadInput } = this.$refs
      uploadInput[0].click()
    },

    handleFileChange(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        this.uploadFiles.push(fileAdapter(files[i]))
      }

      this.resetInput()
    },
    resetInput() {
      const { uploadInput } = this.$refs
      if (uploadInput) {
        uploadInput.value = ''
      }
    },
    setValue(bc) {
      bc.value = +bc.num > 0
      this.busContracts[6].value = !this.busContracts.some(
        (item, index) => +item.num > 0 && index > 0 && index < 6
      )
    },
    // 业务合同类型
    getBusContracts() {
      const res = [
        {
          label: '委托担保合同',
          value: true,
          num: 1,
          showNum: true,
          key: 'entrust_contract_amount',
        },
        {
          label: '反担保保证合同',
          type: 1,
          value: false,
          num: 0,
          showNum: true,
          key: 'gua_ensure_amount',
        },
        {
          label: '反担保质押合同',
          type: 2,
          value: false,
          num: 0,
          showNum: true,
          key: 'gua_pledge_amount',
        },
        {
          label: '反担保抵押合同',
          type: 3,
          value: false,
          num: 0,
          showNum: true,
          key: 'gua_mortgage_amount',
        },
        {
          label: '银担保证合同',
          value: false,
          num: 0,
          showNum: true,
          key: 'bank_gua_amount',
          attach: true,
        },
        { label: '其他', type: 55, value: false, num: 0, showNum: true, key: 'other_amount' },
        {
          label: '无（信用）',
          type: 66,
          value: false,
          num: 0,
          showNum: false,
          key: 'nothing_amount',
        },
      ]
      if (!this.approval.contract_approval_id) {
        this.guardDatas.map(guad => {
          const r = res.find(it => it.type && it.type === +guad.gua_method)
          if (r) {
            r.num++
            r.value = true
          }
        })
        res[6].value = this.guardDatas.length === 0
      } else {
        res.map(item => {
          item.num = this.approval[item.key]
          item.value = +item.num > 0
          return item
        })
        res[6].value = !res.some((item, index) => +item.num > 0 && index > 0 && index < 6)
      }
      return res
    },
    handleDismiss() {
      this.$emit('dismiss', {})
    },

    handleSuccessConfirm() {
      const valid = this.validateContract()
      if (!valid) return

      this.$utils
        .msgbox({
          message: '是否提交？',
          type: 'warning',
          beforeClose: () => this.postApproval(),
        })
        .then(res => {
          this.$message.success('提交成功')
          this.$emit('success', res)
          this.getData()
          this.deleteOssFiles()
          this.uploadFiles = []
        })
        .catch(() => this.$message.error(`提交失败，请重试！`))
    },

    deleteOssFiles() {
      if (!this.deleteFiles.length) return
      deleteOss(this.deleteFiles.map(it => it.url))
    },

    // 提交基础部分
    async postApproval() {
      const attachPromises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/contract/${this.queryId}`,
          type: 0,
          progress: ({ percent }) => {
            it.percent = percent
            it.loading = percent < 100
          },
        })
      )
      const attachment = await Promise.all(attachPromises).then(list => {
        return arrayToString([...this.areadyFiles.map(it => it.url), ...list])
      })
      const date = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd')
      const promises = [
        this.updataApproval({
          customer_related_id: this.queryId,
          res_a_option: this.abComment,
          res_a_date: date,
          res_a_person: this.related.res_a_name,
          res_a_status: 1, // 0 待审批 1 已通过 2 复核不通过
          res_b_option: this.abComment,
          res_b_date: date,
          res_b_person: this.related.res_b_name,
          res_b_status: 1,
          bank_gua_attachment: attachment,
          // 保存数量
          ...this.busContracts.reduce((prev, curr) => {
            prev[curr.key] = curr.num || 0
            return prev
          }, {}),
          gua_des: this.guardCombines
            .map((item, index) => `${index + 1}、${item.combineStr}`)
            .join(','),
        }),
      ]

      if (this.loadVarieties !== +this.entrustContract.loan_varieties) {
        promises.push(
          updateContract(this.contractId, {
            loan_varieties: this.loadVarieties,
          })
        )
      }

      this.saveLoading = true
      return Promise.all(promises)
        .then(() => {
          return updateRelatedContractStatus(this.queryId, 1)
        })
        .finally(() => {
          this.saveLoading = false
        })
    },

    // 更新合同审批内容
    updataApproval(data) {
      // 修改
      if (this.approvalId) {
        return updateApproval(this.approvalId, data)
      }

      // 添加
      return addApproval({
        ...data,
        service_id: this.related.service_id,
        recommend_service: this.related.recommend_service,
        customer_related_id: this.queryId,
      })
    },

    // 合同提交验证
    validateContract() {
      const enumValid = {
        loadVarieties: '请选择贷款品种',
        abComment: '请填写项目经理意见',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },

    getData() {
      const { queryId } = this
      if (!queryId) {
        return
      }

      this.loading = true
      return Promise.all([
        getRelated(queryId),
        getApproval(queryId),
        this.$store.dispatch('getEntrustContract', queryId),
        this.$store.dispatch('getGuardsData', queryId),
      ])
        .then(([related, approval]) => {
          this.related = related
          this.approval = approval
          this.initForm(arrayFromString(approval.bank_gua_attachment))
          this.abComment = approval.res_a_option || ''
          this.$emit('get-data', { related, approval })
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 保证合同字符串拼接
    getGuadGuarantee(data) {
      return `${data.gua_entity} 向 ${this.related.customer_name || ''} 自愿承担连带责任。`
    },
    // 质押合同字符串拼接
    getGuadPledge(data) {
      return `${data.gua_entity_corp || ''} 所持有 ${data.gua_entity || ''} ${
        data.pledge_equity || '-'
      }% 股权，价值 ${data.pledge_funds_cur || ''} 万元，提供质押反担保，办理股权出质登记。`
    },
    // 抵押合同字符串拼接
    getGuadMortgage(data) {
      return `${data.gua_entity} 用 ${data.gua_list_des || ''} 做抵押。`
    },

    handlePrint() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `
        .vertical-align-middle td {vertical-align: middle;}
      `
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.input-td {
  background-color: #ffe;
}
.vertical-align-middle td {
  vertical-align: middle;
}
.variety-selector /deep/ .el-input__inner {
  text-align: center;
}
</style>
